package com.websystique.springboot.controller;

import java.io.IOException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class MultipartController
{
    public static final Logger logger = LoggerFactory.getLogger(MultipartController.class);
    
    @Autowired
    private RestTemplate restTemplate;
    
    @GetMapping("/get")
    public String get()
    {
        return "get";
    }
    
    /**
     * 带MultipartFile post请求接口
     * 
     * @param file
     * @param name
     * @param age
     * @return
     * @see [类、类#方法、类#成员]
     */
    @PostMapping("/post")
    public String post(MultipartFile file, String name, String age)
    {
        logger.info("request file = {},  name = {}, age = {}", (file != null ? file.getOriginalFilename() : ""), name, age);
        return "post";
    }
    
    /**
     * 带MultipartFile post请求接口
     * 
     * @param file
     * @param name
     * @param age
     * @return
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    @PostMapping("/sendPost")
    public String sendPost(MultipartFile multipartFile, String name, String age)
        throws IOException
    {
        String url = "http://127.0.0.1:8080/post";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        ByteArrayResource fileAsResource = new ByteArrayResource(multipartFile.getBytes())
        {
            @Override
            public String getFilename()
            {
                return multipartFile.getOriginalFilename();
            }
            
            @Override
            public long contentLength()
            {
                return multipartFile.getSize();
            }
        };
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("file", fileAsResource);
        multipartRequest.add("name", "girl");
        multipartRequest.add("age", "18");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, headers);
        restTemplate.postForEntity(url, requestEntity, String.class);
        return "sendPost";
    }
    
}
